const app = getApp();

Page({
    data: {
        userInfo: {},
        hostId: ''
    },
    onLoad: function (option) {
        if (option.host) {
            this.setData({
                hostId: option.host
            })
            // 获取用户信息
            this.getUserInfo();
        } else {
            // 获取用户信息
            this.getUserInfo();
        }
    },
    beginStart() {
        if (this.data.userInfo.avatarUrl && this.data.userInfo.nickName) {
            wx.navigateTo({
                url: `/pages/index/index?userInfo=${JSON.stringify(this.data.userInfo)}&hostId=${this.data.hostId}`,
            })
        } else {
            this.getUserProfile().then(() => {
                wx.navigateTo({
                    url: `/pages/index/index?userInfo=${JSON.stringify(this.data.userInfo)}&hostId=${this.data.hostId}`,
                })
            });
        }
    },
    getUserInfo() {
        return new Promise((resolve, reject) => {
            app.cloud({
                name: 'user',
                data: {
                    $url: 'get_user_info'
                }
            }).then(userInfo => {
                app.globalData.userInfo = userInfo;
                this.setData({
                    userInfo: userInfo
                })
                resolve(userInfo);
            }).catch(err => {
                reject(err);
            })
        })
    },
    getUserProfile() {
        if (this.data.userInfo.avatarUrl && this.data.userInfo.nickName) {
            return false;
        }
        return new Promise((resolve, reject) => {
            wx.getUserProfile({
                desc: "完善用户信息",
                success: res => {
                    let userInfo = res.userInfo;
                    this.setData({
                        userInfo: {
                            ...this.data.userInfo,
                            ...userInfo
                        }
                    })
                    resolve(res);
                },
                fail: err => {
                    reject(err);
                }
            })
        })
    }
})